package org.apm.data;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public abstract class Config {
    // IP
    private static final int MAX_IP_PART = 255;
    private static final int MAX_PORT = 65535;
    private static final int DEF_PORT = 9300;

    private static final Logger LOGGER = LogManager.getLogger(Config.class);

    protected Config() {}

    protected static void getHosts(final String hostString, Map<String, Integer> hosts) throws Exception {
        String hostStr = hostString.substring(1, hostString.length() - 1);
        hostStr = hostStr.replace(" ", "");
        for (String host : hostStr.split(",")) {
            String ip = "";
            int port = DEF_PORT;
            if (host.contains(":")) {
                String[] part = host.split(":");
                ip = part[0];
                port = Integer.valueOf(part[1]);
                if (!isIpFormat(ip, port)) {
                    continue;
                }
            } else {
                ip = host;
            }
            hosts.put(ip, port);
        }
        if (hosts.size() < 1) {
            throw new Exception();
        }
    }

    private static boolean isIpFormat(final String ip, final int port) {
        boolean isIpFormat = false;
        if (ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
            String[] str = ip.split("\\.");
            if (Integer.parseInt(str[0]) < MAX_IP_PART) {
                if (Integer.parseInt(str[1]) < MAX_IP_PART) {
                    if (Integer.parseInt(str[2]) < MAX_IP_PART) {
                        if (Integer.parseInt(str[2 + 1]) < MAX_IP_PART) {
                            isIpFormat = true;
                        }
                    }
                }
            }
        }
        if (MAX_PORT < port) {
            isIpFormat = false;
        }
        return isIpFormat;
    }

    protected static Properties loadProperties(final String propertiesFile) {
        InputStream configInStream = Config.class.getClassLoader().getResourceAsStream(propertiesFile);
        Properties props = new Properties();

        try {
            props.load(configInStream);
        } catch (Exception exception) {
            LOGGER.error("Init Config failed.", exception);
        } finally {
            try {
                configInStream.close();
            } catch (Exception exception) {
                LOGGER.error(exception.getMessage(), exception);
            }
        }

        return props;
    }
}
